<template>
	<view class="container">
		<view class="header">
			<text class="title">编辑活动</text>
			<text class="subtitle">修改活动信息，确保内容准确</text>
		</view>

		<uni-forms ref="form" :model="formData" :rules="rules" label-width="90" label-align="right">
			<!-- 活动名称 -->
			<view class="form-card">
				<uni-forms-item label="活动名称" name="name">
					<uni-easyinput v-model:value="formData.name" placeholder="请输入活动名称"
						placeholderStyle="color: #a0b1c5;" :inputBorder="false" class="custom-input" />
				</uni-forms-item>
			</view>

			<!-- 活动地点 -->
			<view class="form-card">
				<uni-forms-item label="活动地点" name="locationName">
					<uni-easyinput v-model:value="formData.locationName" placeholder="请输入活动地点"
						placeholderStyle="color: #a0b1c5;" :inputBorder="false" class="custom-input" />
				</uni-forms-item>
			</view>

			<!-- 日期时间范围 -->
			<view class="form-card">
				<uni-forms-item label="活动时间" name="dateTimeRange" required>
					<uni-datetime-picker v-model="formData.dateTimeRange" type="datetimerange" range-separator="至"
						start-placeholder="开始时间" end-placeholder="结束时间" class="custom-date-picker" />
				</uni-forms-item>
			</view>

			<!-- 状态开关 -->
			<view class="form-card">
				<uni-forms-item label="是否启用" name="isSave">
					<view class="switch-container">
						<switch :checked="formData.isSave" @change="change" color="#1a73e8" />
						<text class="switch-label">{{ formData.isSave ? '已启用' : '已停用' }}</text>
					</view>
				</uni-forms-item>
			</view>

			<!-- 当前位置信息展示 -->
			<view class="form-card location-card">
				<uni-forms-item label="当前位置" name="latitude">
					<view class="location-info">
						<view class="location-icon">
							<uni-icons type="location-filled" size="24" color="#ffffff"></uni-icons>
						</view>
						<view class="location-details">
							<text class="location-label">当前位置坐标</text>
							<view class="coordinates">
								<text class="coordinate">经度: {{ formData.longitude || '--.--' }}</text>
								<text class="coordinate">纬度: {{ formData.latitude || '--.--' }}</text>
							</view>
						</view>
					</view>
				</uni-forms-item>
			</view>

			<!-- 打卡有效范围设置 -->
			<view class="form-card">
				<uni-forms-item label="有效范围" name="validRadius" required>
					<view class="radius-input-container">
						<uni-easyinput type="number" v-model="formData.validRadius" placeholder="请输入有效范围"
							placeholderStyle="color: #a0b1c5;" :inputBorder="false" class="radius-input" />
						<picker class="unit-picker" :range="unitOptions" :value="unitIndex" @change="onUnitChange">
							<view class="picker">
								{{ unitOptions[unitIndex] }}
								<uni-icons type="arrowdown" size="14" color="#7a8fa6"></uni-icons>
							</view>
						</picker>
					</view>
					<view class="range-tip">
						<text>在此范围内可成功打卡</text>
					</view>
				</uni-forms-item>
			</view>

			<!-- 刷新定位按钮 -->
			<view class="refresh-location">
				<button class="location-btn" @click="getCurrentLocation" :loading="isLoadingLocation"
					:disabled="isLoadingLocation">
					<uni-icons type="refresh" size="16" color="#ffffff"></uni-icons>
					<text>{{ isLoadingLocation ? '定位中...' : '刷新定位' }}</text>
				</button>
			</view>

			<!-- 保存按钮 -->
			<button class="submit-btn" type="primary" @click="updateActivity" :loading="isSubmitting"
				:disabled="isSubmitting">
				<text>{{ isSubmitting ? '保存中...' : '保存修改' }}</text>
				<uni-icons v-if="!isSubmitting" type="checkmarkempty" size="16" color="#ffffff"></uni-icons>
			</button>
		</uni-forms>

		<view class="footer-tip">
			<uni-icons type="info" size="14" color="#7a8fa6"></uni-icons>
			<text>提示：活动时间必须在同一天内</text>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				activityId: null,
				locationFetched: false,
				isSubmitting: false,
				isLoadingLocation: false,
				unitOptions: ['米', '公里'], // 单位选项
				unitIndex: 0, // 默认单位索引 (0:米, 1:公里)
				formData: {
					name: '',
					dateTimeRange: [], // 使用日期时间范围字段
					latitude: '',
					longitude: '',
					validRadius: 100, // 默认有效范围100米
					isSave: true
				},
				rules: {
					name: {
						rules: [{
								required: true,
								errorMessage: '请输入活动名称'
							},
							{
								minLength: 2,
								maxLength: 20,
								errorMessage: '名称长度在2到20个字符之间'
							}
						]
					},
					dateTimeRange: {
						rules: [{
							required: true,
							errorMessage: '请选择活动时间'
						}, {
							validateFunction: (rule, value, data, callback) => {
								if (value && value.length === 2) {
									const startDate = value[0].split(' ')[0];
									const endDate = value[1].split(' ')[0];
									if (startDate !== endDate) {
										callback('活动不能跨天，请确保开始和结束在同一天');
									}
								}
								return true;
							}
						}]
					},
					locationName: {
						rules: [{
								required: true,
								errorMessage: '请输入地点名称'
							},
							{
								minLength: 2,
								maxLength: 50,
								errorMessage: '地点名称长度在2到50个字符之间'
							}
						]
					},
					latitude: {
						rules: [{
							required: true,
							errorMessage: '请刷新定位以获取经纬度'
						}]
					},
					validRadius: {
						rules: [{
								required: true,
								errorMessage: '请输入有效范围'
							},
							{
								validateFunction: (rule, value, data, callback) => {
									if (value <= 0) {
										callback('有效范围必须大于0');
									}
									return true;
								}
							}
						]
					}
				}
			}
		},
		onLoad() {
			this.activityId = uni.$router.params._id
			this.getActivityDetail(uni.$router.params._id)
			this.getCurrentLocation()
		},
		methods: {
			change(e) {
				this.formData.isSave = e.detail.value
			},
			async getActivityDetail(_id) {
				uni.showLoading({
					title: '加载中...',
					mask: true
				});

				const obj = uniCloud.importObject('check')
				const res = await obj.getActivitiesById({
					_id: _id
				})

				uni.hideLoading();

				if (res.code === 0 && res.data[0]) {
					const activity = res.data[0];

					// 处理有效范围单位
					let validRadius = activity.validRadius || 500;
					let unitIndex = 0; // 默认单位为米

					// 如果有效范围大于等于1000米，转换为公里显示
					if (validRadius >= 1000) {
						validRadius = (validRadius / 1000).toFixed(2);
						unitIndex = 1; // 设置为公里单位
					}

					// 将日期和时间范围组合成 dateTimeRange 格式
					this.formData = {
						...activity,
						dateTimeRange: [
							`${activity.date} ${activity.timeRange.start}`,
							`${activity.date} ${activity.timeRange.end}`
						],
						validRadius: validRadius
					};

					// 设置单位索引
					this.unitIndex = unitIndex;
				} else {
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					})
				}
			},
			async getCurrentLocation() {
				this.isLoadingLocation = true;
				uni.showLoading({
					title: '定位中...',
					mask: true
				});
				try {
					const res = await uni.getLocation({
						type: 'wgs84',
						geocode: true
					})
					this.formData.latitude = res.latitude.toFixed(6)
					this.formData.longitude = res.longitude.toFixed(6)
					this.locationFetched = true
					uni.showToast({
						title: '定位成功',
						icon: 'success'
					});
				} catch (err) {
					uni.showToast({
						title: '获取位置失败',
						icon: 'none'
					})
					this.locationFetched = true
				} finally {
					this.isLoadingLocation = false;
					uni.hideLoading();
				}
			},

			// 单位选择变化
			onUnitChange(e) {
				this.unitIndex = e.detail.value;
				// 单位切换时自动转换数值
				if (this.formData.validRadius) {
					if (this.unitIndex === 0) { // 切换到米
						this.formData.validRadius = this.formData.validRadius * 1000;
					} else { // 切换到公里
						this.formData.validRadius = this.formData.validRadius / 1000;
					}
					// 保留两位小数
					this.formData.validRadius = parseFloat(this.formData.validRadius.toFixed(2));
				}
			},

			async updateActivity() {
				if (this.isSubmitting) return;
				this.isSubmitting = true;

				try {
					const valid = await this.$refs.form.validate();
					if (!valid) {
						uni.showToast({
							title: '表单验证失败',
							icon: 'none'
						})
						return;
					}

					// 拆分日期时间范围
					const [startDateTime, endDateTime] = this.formData.dateTimeRange;

					// 将有效范围统一转换为米
					let validRadiusInMeters = this.formData.validRadius;
					if (this.unitIndex === 1) { // 当前单位是公里
						validRadiusInMeters = this.formData.validRadius * 1000;
					}

					// 准备更新数据
					const updateData = {
						...this.formData,
						date: startDateTime.split(' ')[0],
						timeRange: {
							start: startDateTime.split(' ')[1],
							end: endDateTime.split(' ')[1]
						},
						validRadius: validRadiusInMeters // 使用转换后的米单位
					};

					// 删除不需要的字段
					delete updateData.dateTimeRange;
					delete updateData._id;

					const obj = uniCloud.importObject('check')
					const res = await obj.updateActivity({
						_id: this.activityId,
						data: updateData
					})

					if (res.code === 0) {
						uni.showToast({
							title: '更新成功',
							icon: 'success',
							duration: 1500
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					} else {
						throw new Error(res.errMsg || '更新失败');
					}
				} catch (err) {
					uni.showToast({
						title: err.message || '更新失败',
						icon: 'none'
					})
				} finally {
					this.isSubmitting = false;
				}
			}
		}
	}
</script>

<style scoped>
	/* 整体容器 */
	.container {
		padding: 25rpx 30rpx 50rpx;
		background: linear-gradient(to bottom, #f0f8ff, #ffffff);
		min-height: 100vh;
	}

	/* 头部标题 */
	.header {
		padding: 40rpx 20rpx 30rpx;
		text-align: center;
	}

	.title {
		font-size: 42rpx;
		font-weight: bold;
		color: #1a73e8;
		display: block;
		letter-spacing: 1rpx;
	}

	.subtitle {
		font-size: 26rpx;
		color: #7a8fa6;
		display: block;
		margin-top: 15rpx;
	}

	/* 表单卡片样式 */
	.form-card {
		background-color: #ffffff;
		border-radius: 16rpx;
		padding: 20rpx 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 4rpx 20rpx rgba(26, 115, 232, 0.08);
		border: 1rpx solid #e6f0ff;
	}

	.location-card {
		background: linear-gradient(to right, #e6f2ff, #f0f8ff);
		border: 1rpx solid #c2e0ff;
	}

	/* 自定义输入框 */
	.custom-input {
		border-radius: 12rpx;
		background-color: #f8fbff;
		border: 1rpx solid #d9e7ff;
		padding: 20rpx 25rpx;
	}

	/* 日期选择器 */
	.custom-date-picker {
		border-radius: 12rpx;
		background-color: #f8fbff;
		border: 1rpx solid #d9e7ff;
		padding: 20rpx 25rpx;
	}

	/* 开关容器 */
	.switch-container {
		display: flex;
		align-items: center;
	}

	.switch-label {
		margin-left: 20rpx;
		color: #1a3e78;
		font-size: 28rpx;
	}

	/* 位置信息样式 */
	.location-info {
		display: flex;
		align-items: center;
		padding: 20rpx 0;
	}

	.location-icon {
		width: 70rpx;
		height: 70rpx;
		border-radius: 50%;
		background: linear-gradient(135deg, #1a73e8, #4dabf7);
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 25rpx;
		box-shadow: 0 4rpx 12rpx rgba(26, 115, 232, 0.25);
	}

	.location-details {
		flex: 1;
	}

	.location-label {
		font-size: 28rpx;
		color: #4a6fa9;
		display: block;
		font-weight: 500;
		margin-bottom: 10rpx;
	}

	.coordinates {
		display: flex;
		flex-wrap: wrap;
	}

	.coordinate {
		font-size: 26rpx;
		color: #2c3e50;
		background-color: rgba(255, 255, 255, 0.7);
		padding: 8rpx 20rpx;
		border-radius: 30rpx;
		margin-right: 15rpx;
		margin-bottom: 10rpx;
		font-family: monospace;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
	}

	/* 有效范围输入样式 */
	.radius-input-container {
		display: flex;
		align-items: center;
	}

	.radius-input {
		flex: 1;
		border-radius: 12rpx;
		background-color: #f8fbff;
		border: 1rpx solid #d9e7ff;
		padding: 20rpx 25rpx;
		margin-right: 20rpx;
	}

	.unit-picker {
		width: 140rpx;
		background-color: #f8fbff;
		border: 1rpx solid #d9e7ff;
		border-radius: 12rpx;
		padding: 20rpx 25rpx;
		color: #2c3e50;
	}

	.picker {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.range-tip {
		font-size: 24rpx;
		color: #7a8fa6;
		margin-top: 15rpx;
		padding-left: 5rpx;
	}

	/* 按钮样式 */
	.location-btn {
		background: linear-gradient(to right, #4dabf7, #1a73e8);
		color: #ffffff;
		border: none;
		border-radius: 50rpx;
		padding: 20rpx 40rpx;
		font-size: 28rpx;
		box-shadow: 0 4rpx 15rpx rgba(26, 115, 232, 0.3);
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 30rpx auto;
		width: 60%;
	}

	.location-btn[disabled] {
		opacity: 0.7;
	}

	.location-btn text {
		margin-left: 10rpx;
	}

	.submit-btn {
		background: linear-gradient(to right, #1a73e8, #0d5cb6);
		color: #ffffff;
		border: none;
		border-radius: 50rpx;
		padding: 25rpx 0;
		font-size: 32rpx;
		font-weight: 500;
		box-shadow: 0 6rpx 20rpx rgba(26, 115, 232, 0.4);
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 50rpx auto 30rpx;
		width: 85%;
	}

	.submit-btn[disabled] {
		opacity: 0.8;
	}

	.submit-btn text {
		margin-right: 15rpx;
	}

	/* 底部提示 */
	.footer-tip {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 20rpx;
		font-size: 24rpx;
		color: #7a8fa6;
	}

	.footer-tip text {
		margin-left: 10rpx;
	}
</style>